package org.example;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class Controller extends Thread{
    /**
     * Redis 服务器地址
     */
    private final String REDIS_HOST ;
    /**
     * Redis 服务器端口
     */
    private final int REDIS_PORT ;
    /**
     * Redis 密码
     */
    private final String REDIS_PWD;
    /**
     * 消息队列服务器地址
     */
    private final String MQ_HOST ;
    /**
     * 消息队列服务器端口
     */
    private final int MQ_PORT ;
    /**
     * 消息队列用户名
     */
    private final String MQ_USERNAME ;
    /**
     * 消息队列密码
     */
    private final String MQ_PWD  ;
    /**
     * 当前构件队列名称
     */
    public String queue;
    /**
     * 是否工作
     */
    boolean toWork=false;
    /**
     * 接收者
     */
    Receiver receiver=null;
    /**
     * 发送者
     */
    Sender sender=null;

    Jedis  jedis;
    /**
     * 时间戳
     */
    private int TIMESTAMP = 1;
    private final String NAVI_QUEUE = "navigator";
    private final String VIEW_QUEUE = "UpdateView";
    private final String QUEUE_PREFIX = "card";

    public Controller(String REDIS_HOST, int REDIS_PORT, String REDIS_PWD, String MQ_HOST, int MQ_PORT, String MQ_USERNAME, String MQ_PWD, String queue) {
        this.REDIS_HOST = REDIS_HOST;
        this.REDIS_PORT = REDIS_PORT;
        this.REDIS_PWD = REDIS_PWD;
        this.MQ_HOST = MQ_HOST;
        this.MQ_PORT = MQ_PORT;
        this.MQ_USERNAME = MQ_USERNAME;
        this.MQ_PWD = MQ_PWD;
        this.queue = queue;
    }

    /**
     * 开始工作
     */
    public void StartWork() {
        //连接redis服务器
        jedis = new Jedis(REDIS_HOST, REDIS_PORT);
        jedis.connect();
        // 启动一个发送器
        sender = new Sender(MQ_HOST, MQ_PORT, MQ_USERNAME, MQ_PWD);
        sender.startWork();

        // 启动一个接收器
        receiver = new Receiver(MQ_HOST, MQ_PORT, MQ_USERNAME, MQ_PWD, queue);
        receiver.startListern();

        // 开启工作线程
        toWork = true;
        this.start();
    }

    /**
     * 停止工作，释放连接
     */
    public void StopWork() {
        if (receiver != null) {
            receiver.stopListern();
            receiver = null;
        }

        if(sender != null){
            sender.StopWork();
            sender = null;
        }

        toWork = false;

    }
    public void run() {
        while (toWork) {
            List<String> carIds = getCarIds();

            for (String carId : carIds) {
                String routeListKey = "car:" + carId + ":tasks";

                // 不加锁，直接检查是否存在任务
                Boolean keyExists = jedis.exists(routeListKey);
                if (keyExists) {
                    String nextPosition = "Move " + TIMESTAMP;
                    sendMoveCommand(carId, nextPosition);
                    sendViewUpdate(carId, nextPosition);
                } else {
                    // 没有任务才发导航请求
                    sendNaviRequest(carId);
                }
            }

            try {
                Thread.sleep(1000);
                TIMESTAMP++;
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }


    private void sendNaviRequest(String carId) {
        String carName=QUEUE_PREFIX+carId;
        System.out.println(carName);
        sender.SendAMsg(NAVI_QUEUE,carName);
    }

    private void sendViewUpdate(String carId, String nextPosition) {
        sender.SendAMsg(VIEW_QUEUE,VIEW_QUEUE);
    }

    private void sendMoveCommand(String carId, String nextPosition) {
        String queueName = QUEUE_PREFIX + carId;

        sender.SendAMsg(queueName,nextPosition);
    }

    private List<String> getCarIds() {
        Set<String> keys = jedis.keys("car:*:position"); // 获取匹配的键集合
        List<String> carIds = new ArrayList<>();
        for (String key : keys) {
            String[] parts = key.split(":");
            if (parts.length >= 3 && "position".equals(parts[2])) { // 确保格式正确
                carIds.add(parts[1]); // 提取 {id}
            }
        }

        return carIds;
    }

}